import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime

file_name = os.path.basename(__file__)
dir = file_name + '.d'
os.makedirs(dir, exist_ok=True)
name = str(datetime.datetime.now()) + '.avi'
name = ensure_filename(name)
path = os.path.join(dir, name)
print(path)

cap = cv.VideoCapture(0)

if not cap.isOpened():
    print('Cannot open cam!')
    sys.exit(1)

MARGIN = 32
W = 640
H = 480
LINE = 2
FPS = 25
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter(path, fourcc, FPS, (640, 480))


def my_darw_(mat):
    cv.rectangle(mat, (MARGIN, MARGIN), (W - MARGIN, H - MARGIN), (0, 0, 255), LINE)


LENGTH = 3  # how many seconds
i = -1
interval = 1000 // FPS
first_close = True
while True:
    i += 1
    ret, frame = cap.read()
    frame = cv.flip(frame, 1)  # ATTENTION flip

    if not ret:
        print('Cannot read from cam, exiting...')
        break

    # common
    my_darw_(frame)
    dt = str(datetime.datetime.now())
    cv.putText(frame, dt, (W // 2, MARGIN - LINE * 2), cv.FONT_HERSHEY_PLAIN, 1,
               (0, 0, 255), 1, cv.LINE_4, False)

    if i < FPS * LENGTH:
        tag = 'saving...'

        # rec sign
        cv.putText(frame, 'REC', (MARGIN, MARGIN - LINE), cv.FONT_HERSHEY_PLAIN, 2,
                   (0, 0, 255), 3, cv.LINE_AA, False)
        cv.circle(frame, (int(np.ceil(MARGIN * 3.5)), MARGIN // 2),
                  int(np.ceil(MARGIN * 0.4)), (0, 0, 255), -1)

        out.write(frame)
    else:
        if first_close:
            first_close = False
            cv.destroyWindow('Cam ' + tag)
            out.release()
        tag = 'saved'

    cv.imshow('Cam ' + tag, frame)

    k = cv.waitKey(interval) & 0xFF
    if k == 27 or k == ord('q') or k == ord('Q'):
        break

cap.release()
cv.destroyAllWindows()
